import requests
import json
import requests
import base64

import Config


class CHATGPT3:
    def __init__(self):
        self.url = "https://oa.api2d.net/v1/chat/completions"
        self.headers = {
            'Authorization': 'Bearer fk200998-Zf51oriBnQKyX10pSCIktPUovHP3U0Ij',
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'Content-Type': 'application/json'
        }

    def answer(self, ask, org_ask, history):
        ask = str(ask)
        org_ask = str(org_ask)
        history_dic = {
            "model": "gpt-3.5-turbo",
            "messages": [],
            "safe_mode": False,
            "stream": True
        }
        # 构建历史对话消息
        for cop in history:
            history_dic["messages"].append({"role": "user", "content": str(cop[0])})
            history_dic["messages"].append({"role": "assistant", "content": str(cop[1])})
        # 添加当前提问
        history_dic["messages"].append({"role": "user", "content": str(ask)})

        payload = json.dumps(history_dic)
        response = requests.post(self.url, headers=self.headers, data=payload)

        # 确保请求成功
        response.raise_for_status()
        history.append([org_ask, ""])
        # 流式解析
        tmpdata = ""
        for chunk in response.iter_lines():
            chunk = chunk.decode("utf-8")
            data = chunk[5:]
            try:
                datadic = json.loads(data)
                res = datadic["choices"][0]["delta"]["content"]
                history[-1][-1] += res
                yield history
            except:
                pass

    def answer_no_stream(self, ask, history):
        ask=str(ask)
        history_dic = {
            "model": "gpt-3.5-turbo",
            "messages": [],
            "safe_mode": False,
        }
        # 构建历史对话消息
        for cop in history:
            history_dic["messages"].append({"role": "user", "content": str(cop[0])})
            history_dic["messages"].append({"role": "assistant", "content": str(cop[1])})
        # 添加当前提问
        history_dic["messages"].append({"role": "user", "content": ask})

        payload = json.dumps(history_dic)
        response = requests.post(self.url, headers=self.headers, data=payload)

        # 确保请求成功
        response.raise_for_status()

        # 解析回答
        try:
            answer_data = response.json()["choices"][0]["message"]["content"]
        except KeyError:
            print("Error parsing response from the server.")
            answer_data = ""

        return answer_data
